<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/21 10:25
 * Remark:
 */

namespace App\Service\Company;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Company\CompanyModel;
use App\Models\Department\DepartmentModel;
use App\Scopes\MediationStaffScope;
use App\ServiceChecker\Company\CompanyLegitimacy;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\common\cTesting;
use Lcobucci\JWT\Token;


class CompanyService
{
    private CompanyModel $_companyModel;
    private CompanyLegitimacy $companyLegitimacy;

    public function __construct()
    {
        $this->_companyModel = new CompanyModel();
        $this->companyLegitimacy = new CompanyLegitimacy();
    }

    /**
     * 声明部门模型
     * @return DepartmentModel
     */
    private function _createDeptModel(): DepartmentModel
    {
        return new DepartmentModel();
    }

    /**
     * 获取公司等级
     * @param $companyParentId
     * @return string
     */
    private function _getCompanyLevel($companyParentId): string
    {
        $companyParentInfo = $this->_companyModel->getCompanyInfoModelByCompanyId($companyParentId,['company_id','company_level']);
        // 计算公司等级
        // 当公司等级为2级时 设置等级为 父公司.1 当公司为2级以上时 设置等级为 父公司.1.1
        if($companyParentInfo['company_level'] == 1){
            $companyLevel = $companyParentInfo['company_id'].".";
        }else{
            $companyLevel = $companyParentInfo['company_level'].$companyParentInfo['company_id'].".";
        }
        return $companyLevel;
    }

    /**
     *  新增公司校验
     * @param $args
     */
    private function checkerAddCompanyService($args){
        $this->companyLegitimacy->verifyCompanyNameIsExists($args['company_name']);
        $this->companyLegitimacy->verifyCompanyCodeIsExists($args['company_code']);
//        if($args['company_parent_id']){
//            $this->companyLegitimacy->verifyCompanyHasChildIsExists($args['company_parent_id']);
//        }
    }

    /**
     * 新增公司Service
     * @param $companyData
     * @return bool
     */
    public function addCompanyService($companyData): bool
    {
        // 校验数据
        $this->checkerAddCompanyService([
            'company_name' => $companyData['company_name'],
            'company_code' => $companyData['company_code'],
//            'company_parent_id' => $companyData['company_parent_id'] ?? false,
        ]);
        // 计算公司等级
        if(!isset($companyData['company_parent_id']) || $companyData['company_parent_id'] ==0){
            $companyData['company_parent_id'] = 0;
            $companyData['company_level'] = 1;
        }else{
            $companyData['company_level'] = $this->_getCompanyLevel($companyData['company_parent_id']);
        }

        $companyData = [
            $this->_companyModel->company_name = $companyData['company_name'],
            $this->_companyModel->company_parent_id = $companyData['company_parent_id'] ?? 0,
            $this->_companyModel->company_level = $companyData['company_level'],
            $this->_companyModel->company_code = $companyData['company_code'],
        ];

        $companyRes = $this->_companyModel->addCompanyModel($companyData);
        if(!$companyRes){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "新增公司失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        return true;
    }

    /**
     * 编辑公司验证
     * @param $args
     */
    private function checkerEditCompanyService($args){
        $this->companyLegitimacy->verifyCompanyIsExists($args['company_id']);
        if($args['company_name']){
            $this->companyLegitimacy->verifyCompanyEdit($args['company_name'],$args['company_id']);
        }
        if($args['company_parent_id']){
            $this->companyLegitimacy->verifyCompanyParentIsLegal($args['company_id'],$args['company_parent_id']);
        }
    }

    /**
     * 编辑公司
     * @param $companyData
     * @return bool
     */
    public function editCompanyService($companyData) :bool{

        if(isset($companyData["company_name"]) && empty($companyData["company_name"])){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "公司名称",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }

        unset($companyData['company_code']);
        $this->checkerEditCompanyService([
            'company_id' => $companyData['company_id'],
            'company_name' => $companyData['company_name'] ?? false,
            'company_parent_id' => $companyData['company_parent_id'] ?? false
        ]);
        unset($companyData['status']);
        $updateData = $companyData;
        // 计算公司等级
        if(isset($updateData['company_parent_id']) && $updateData['company_parent_id'] !=0){
            $updateData['company_level'] = $this->_getCompanyLevel($updateData['company_parent_id']);
        }
        $companyRes = $this->_companyModel->editCompanyEdit($updateData);
        if(!$companyRes){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "编辑公司失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        return true;
    }

    /**
     * 删除公司校验
     * @param $args
     */
    private function checkerDeleteService($args){
        $this->companyLegitimacy->verifyCompanyIsExists($args['company_id']);
        $this->companyLegitimacy->verifyCompanyHasChildIsExists($args['company_id']);
    }

    /**
     * 删除公司
     * @param $companyId
     * @return bool
     */
    public function patchEditCompanyService($companyId): bool
    {
        $this->checkerDeleteService([
            'company_id' => $companyId
        ]);

        $companyRes = $this->_companyModel->editCompanyEdit([
            'company_id' => $companyId,
            'status' => BaseConsts::STATUS_DELETE
        ]);
        if(!$companyRes){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "删除公司失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        return true;
    }

    /**
     * 批量删除公司校验
     * @param $args
     */
    private function checkerBulkDeleteCompany($args){
        foreach($args['company_ids'] as $company_id){
            $this->companyLegitimacy->verifyCompanyIsExists($company_id);
            $this->companyLegitimacy->verifyCompanyHasChildIsExists($company_id);
        }
    }

    /**
     * 批量删除公司
     * @param $companyIds
     * @return mixed
     */
    public function bulkDeleteCompany($companyIds): mixed
    {
        $this->checkerBulkDeleteCompany([
            'company_ids' => $companyIds
        ]);
        return $this->_companyModel->bulkDeleteCompany(
            $companyIds,[
            'status' => BaseConsts::STATUS_DELETE
        ]);
    }

    /**
     * 获取公司详情
     * @param $companyId
     * @return mixed
     */
    public function getCompanyInfoService($companyId): mixed
    {
        $isExist = $this->_companyModel->isExistByCondition([
            'company_id' => $companyId,
        ]);

        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "当前公司不存在或已存在",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        $companyInfo = $this->_companyModel->getCompanyInfoModelByCompanyId($companyId,[
            'company_id',
            'company_id as company_code',
            'company_name',
            'company_level as company_level_name',
            'company_parent_id',
            'company_parent_id as company_parent_name',
            'created_at',
        ]);
        $companyInfo['department_list'] = $this->_createDeptModel()->getDepartmentMenuByCompanyId($companyId,[
            'department_id',
            'department_id as key',
            'department_id as department_code',
            'department_name',
            'department_parent_id',
            'department_parent_id as department_parent_name',
        ]);
        return $companyInfo;
    }

    /**
     * 公司下拉
     * @return mixed
     */
    public function getCompanySelect(): mixed
    {
        return $this->_companyModel->getCompanySelect();
    }

    /**
     * 公司下拉
     * @return mixed
     */
    public function getCompanySelectByLogin(): mixed
    {
		# testing go ...	=> by breezeer @2022.12.15
		# 
		# 
		#
		(new cTesting())->go();

		#
		#
		#
        return $this->_companyModel->getCompanySelectByLogin();
    }


    /**
     * 获取公司列表
     * @param $pageSize
     * @param $filters
     * @return mixed
     */
    public function getCompanyList($pageSize,$filters): mixed
    {
        $query = $this->_companyModel->select(
            [
                'company_id',
                'company_code',
                'company_id as key',
                'company_name',
                'company_level as company_level_name',
                'company_parent_id',
                'company_parent_id as company_parent_name',
                'created_at'
            ])  # 禁止全局 手动处理
            ->withoutGlobalScope(MediationStaffScope::class)
            ->where('company_id',TokenFuc::getCurrentStaffInfo()['company_id']);
        if($filters){
            $filters = json_decode($filters,true);
            if(isset($filters['company_name']) && $filters['company_name']){
                $query = $query->where('company_name','like','%'.$filters['company_name'].'%');
            }
            if(isset($filters['company_parent_id']) && $filters['company_parent_id']){
                $query = $query->where('company_parent_id',$filters['company_parent_id']);
            }
        }

        $companyList =  $this->_companyModel->getCompanyList($query,$pageSize)->toArray();
        if($companyList['data']) {
            foreach($companyList['data'] as $companyKey => $company){
                $companyList['data'][$companyKey]['department_list'] = $this->_createDeptModel()->getDepartmentMenuByCompanyId($company['company_id'],[
                    'department_id',
                    'department_id as department_code',
                    'department_name',
                    'department_parent_id',
                    'department_parent_id as department_parent_name',
                ]);
            }
        }
        return $companyList;
    }

    /**
     * 获取全部下级公司
     * @param $companyId
     * @return array
     */
    public function getCompanyAllNextByCompanyId($companyId): array
    {
        // 校验当前公司是否属于一级
        $hasNextCompany =  $this->_companyModel->getCompanyInfoModelByCompanyId($companyId,['company_parent_id'])['company_parent_id'];
        // 如果不属于一级公司 则拼接字符串.
        if($hasNextCompany){
            $companyId = ".".$companyId;
        }
        return array_column($this->_companyModel->getCompanyAllNextByCompanyId($companyId)->toArray(),"company_id");
    }

    /**
     * 获取下一级公司
     * @param $companyId
     * @return array
     */
    public function getCompanyNext($companyId): array
    {
        return array_column($this->_companyModel->getCompanyNextByCompanyId($companyId)->toArray(),"company_id");
    }

}